<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <el-icon @click="onClickBack">
          <ArrowLeftBold />
        </el-icon>
        <div>机构管理</div>
      </div>
    </template>
    <div class="countent">
      <div class="leftBox">
        <div class="leftBox-header">
          <div>机构菜单</div>
          <!-- <div>
            <Plus
              style="width: 20px; margin-right: 20px"
              @click="openAddDialog"
            />

            <el-dropdown>
              <More class="more" style="width: 20px" />
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="rename">重命名</el-dropdown-item>
                  <el-dropdown-item @click="deleteThis">删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div> -->
        </div>
        <el-tree
          style="max-width: 600px; font-size: 16px"
          :data="treeData"
          :props="defaultProps"
          :highlight-current="true"
          node-key="label"
          default-expand-all
          @node-click="handleNodeClick"
        >
        </el-tree>
      </div>
      <div class="rightBox">
        <div class="breadcrumb" v-if="checkTree.name">
          <el-breadcrumb class="breadcrumb-dome" separator=">">
            <el-breadcrumb-item>{{ checkTree.parentName }}</el-breadcrumb-item>
            <el-breadcrumb-item>{{ checkTree.name }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div class="checkList">
          <el-checkbox
            v-model="checkAll"
            @change="handleCheckAllChange"
            :disabled="rules.every((item) => item.readyonly)"
          >
            所有权限
          </el-checkbox>

          <el-checkbox-group
            v-model="checkedFirst"
            @change="handleCheckedFirstChange"
          >
            <div
              class="checkList-item"
              v-for="(item, index) in rules"
              :key="index"
            >
              <!-- 每一个一级 -->
              <el-checkbox
                v-model="checkItem"
                :label="item.name"
                @change="handleSecondChange"
                :disabled="item.readyonly"
                :checked="true"
              >
                <div class="permisstion">
                  <div>{{ item.name }}</div>
                  <div class="plathName" v-if="item.platname">
                    {{ item.platname }}
                  </div>
                </div>
              </el-checkbox>

              <!-- 每一个二级 -->
              <el-checkbox-group
                v-model="checkedSecond"
                @change="handleCheckedSecondChange(item)"
              >
                <div class="checkList-item-children">
                  <div
                    class="checkList-item-children1"
                    v-show="item.children[1]?.length > 0"
                  >
                    <span class="checkList-item-children-span">菜单 </span>
                    <el-checkbox
                      v-for="(item2, index2) in item.children[1]"
                      :key="index2"
                      :label="item2.name"
                      @change="secondChildrenChange(item2)"
                      :checked="item2.roleIsHavePermission == 1"
                      :model="item2.roleIsHavePermission"
                      :disabled="item2.readyonly"
                    >
                      <div class="permisstion">
                        <div>{{ item2.name }}</div>
                        <div class="plathName" v-if="item2.platname">
                          {{ item2.platname }}
                        </div>
                      </div>
                    </el-checkbox>
                  </div>
                  <div
                    class="checkList-item-children2"
                    v-show="item.children[2]?.length > 0"
                  >
                    <span class="checkList-item-children-span">功能</span>
                    <el-checkbox
                      v-for="(item3, index3) in item.children[2]"
                      :key="index3"
                      :label="item3.name"
                      @change="secondChildrenChange(item3)"
                      :checked="item3.roleIsHavePermission == 1"
                      :model="item3.roleIsHavePermission"
                      :disabled="item3.readyonly"
                    >
                      <div class="permisstion">
                        <div>{{ item3.name }}</div>
                        <div class="plathName" v-if="item3.platname">
                          {{ item3.platname }}
                        </div>
                      </div>
                    </el-checkbox>
                  </div>
                </div>
              </el-checkbox-group>
            </div>
          </el-checkbox-group>
        </div>
        <el-button
          class="save"
          type="primary"
          @click="saveData"
          :disabled="rules.every((item) => item.readyonly)"
          >保存</el-button
        >
      </div>
    </div>

    <!-- 点击添加弹窗 -->
    <el-dialog
      class="dialog"
      v-model="dialogVisible"
      title="创建角色分类"
      width="500"
    >
      <div class="dialog-countent">
        <div class="first-order order">
          <span>一级分类</span>
          <el-select
            :popper-options="{
              modifiers: [
                { name: 'computeStyles', options: { adaptive: false } },
              ],
            }"
            class="first-order-select"
            v-model="addGroup"
            placeholder="未选择"
            size="large"
            style="width: 240px"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </div>
        <div class="Second-order order">
          <span>二级分类</span>
          <el-input
            class="Second-order-input"
            v-model="addName"
            style="width: 240px"
            placeholder="请输入二级名称分类"
          />
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="addAuthorityRole(addGroup, addName)"
          >
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 点击重命名弹窗 -->
    <el-dialog
      class="dialog"
      v-model="dialogVisible2"
      title="创建角色分类"
      width="500"
    >
      <div class="dialog-countent">
        <div class="Second-order order">
          <span>二级分类</span>
          <el-input
            class="Second-order-input"
            v-model="changeName"
            style="width: 240px"
            placeholder="请输入二级名称分类"
          />
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible2 = false">取消</el-button>
          <el-button type="primary" @click="saveChangeName"> 保存 </el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>
<script setup>
import { useRouter, useRoute } from 'vue-router';
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import {
  currentRoleList,
  currentRuleList,
  roleCreate,
  //   roleDel,
  appRuleUpdate,
} from '@/api/permission/permission.js';
const route = useRoute();

const { proxy } = getCurrentInstance();
// 选择所有
const checkAll = ref(false);
// 选择一级分类
const checkItem = ref(false);
// 选中的
const checkedFirst = ref([]);

// 判断是否是管理员权限
const administrators = ref('');

// 选中的id的集合
const checkIds = ref([]);
// 弹框select内容
const options = ref([]);
const defaultProps = {
  children: 'children',
  label: 'name',
};
const dialogVisible = ref(false);
const dialogVisible2 = ref(false);
const disabled = ref(false);
// 新增分类分组
const addGroup = ref('');
// 新增分类名
const addName = ref('');
const changeName = ref('');
const router = useRouter();
// 被选中的树 id
const checkedKeyId = ref('');
// 被选中的树
const checkedKey = ref({});
// 所有权限的列表
const rules = ref([]);

// 二级分类名称的集合
const secondTreeName = ref([]);
// 选中树
const checkTree = ref({});

const treeData = ref([]);
// 点击左侧树选中的数据
const handleNodeClick = (data) => {
  if (data.level == '2') {
    checkTree.value = data;
    // 先清空列表
    checkedFirst.value = [];
    checkedSecond.value = [];

    checkedKey.value = data;
    checkedKeyId.value = data.id;
    if (checkedKeyId.value == '2') {
      disabled.value = true;
    } else {
      disabled.value = false;
    }
    permissionList();
  }
};

// 获取角色权限列表
function rolesList() {
  currentRoleList({ id: route.query.id }).then((res) => {
    treeData.value = res.data;
    for (const v of treeData.value) {
      for (const i of v.children) {
        secondTreeName.value.push(i.name);
        if (i.isroot == '1') {
          administrators.value = i.id;
        }
      }
    }
    options.value = res.data.filter((item) => {
      if (item.isroot != 1) {
        return item;
      } else {
        return;
      }
    });
    permissionList();
  });
}
rolesList();

// 获取角色权限列表
function permissionList() {
  // 先清空选中列表
  checkedFirst.value = [];
  currentRuleList({
    // 第一次加载，先取管理员的权限列表
    roleId: checkedKeyId.value ? checkedKeyId.value : administrators.value,
  }).then((res) => {
    rules.value = res.data.data;
    // 回显，选中有权限的
    checkedFirst.value = res.data.data
      .map((item) => (item.roleIsHavePermission == 1 ? item.name : ''))
      .filter((item) => item != '');
    checkAll.value = checkedFirst.value.length == rules.value.length;
    // 回显的时候，选中的
    const a = [];

    // 所有的数据重构一下
    for (const v of res.data.data) {
      v.childrenItem = [];
      if (v.children[1].length > 0) {
        for (const i of v.children[1]) {
          if (i.roleIsHavePermission == 1) {
            a.push(i.id);
            v.childrenItem.push(i.name);
            handleSecondChange(
              true,
              { target: { _value: v.name, value: v.name } },
              true
            );
            handleCheckedSecondChange(i);
          }
        }
      }
      if (v.children[2].length > 0) {
        for (const i of v.children[2]) {
          if (i.roleIsHavePermission == 1) {
            a.push(i.id);
            v.childrenItem.push(i.name);
            handleSecondChange(
              true,
              { target: { _value: v.name, value: v.name } },
              true
            );
            handleCheckedSecondChange(i);
          }
        }
      }
      checkIds.value = [...new Set(a)];
    }
  });
}

// 打开添加弹窗
// function openAddDialog() {
//   dialogVisible.value = true;
//   addGroup.value = '';
//   addName.value = '';
// }

// // 打开重命名弹窗
// function rename() {
//   // 判断是否选中
//   // 判断选中的是否为一级菜单
//   if (
//     checkedKeyId.value == '' ||
//     treeData.value.filter((item) => item.id == checkedKeyId.value)[0]
//       ?.parentId == 0
//   ) {
//     ElMessage.warning('请选择二级分类');
//   } else {
//     for (const v of treeData.value) {
//       for (const vv of v.children) {
//         if (vv.id == checkedKeyId.value) {
//           changeName.value = vv.name;
//         }
//       }
//       dialogVisible2.value = true;
//     }
//   }
// }

// 返回
function onClickBack() {
  router.back();
}

// 添加权限角色
const addAuthorityRole = (addGroup, addName) => {
  if (addGroup == '' || addName == '') {
    ElMessage.warning('请输入完整信息');
  } else {
    proxy.$modal
      .confirm(`确认添加?`)
      .then(function () {
        const data = {
          parentId: addGroup,
          parentName: options.value.filter((item) => item.id == addGroup)[0]
            .name,
          name: addName,
        };
        if (secondTreeName.value.includes(addName) == true) {
          ElMessage.warning('该分类已存在！');
          return;
        } else {
          roleCreate(data).then((res) => {
            if (res.code == 20000) {
              rolesList();
              ElMessage.success('添加成功！');
            }
          });
        }

        dialogVisible.value = false;
        return;
      })
      .catch(() => {});
  }
};

// // 删除权限角色
// function deleteThis() {
//   if (checkedKeyId.value == '') {
//     ElMessage.warning('请选择二级分类');
//   } else if (!!treeData.value.find((i) => i.id == checkedKeyId.value)) {
//     ElMessage.warning('该分类无法删除！');
//     return;
//   } else if (checkedKeyId.value == '2') {
//     ElMessage.warning('该分类无法删除！');
//     return;
//   } else {
//     const firstName = checkTree.value.parentName;
//     const secondName = checkTree.value.name;
//     proxy.$modal
//       .confirm('是否删除' + '(' + firstName + '>' + secondName + ')' + '?')
//       .then(function () {
//         roleDel({ id: checkedKeyId.value }).then((res) => {
//           if (res.code == 20000) {
//             rolesList();
//             ElMessage.success('删除成功！');
//             // 清空权限列表
//             checkedKeyId.value = '';
//             // 恢复默认点击管理员
//             for (const v of treeData.value) {
//               for (const i of v.children) {
//                 if (i.isroot == '1') {
//                   checkTree.value = i;
//                 }
//               }
//             }
//             permissionList();
//           }
//         });
//         return;
//       })
//       .catch(() => {});
//   }
// }

// 重命名
const saveChangeName = () => {
  if (changeName.value == '') {
    ElMessage.warning('请输入完整信息');
  } else {
    proxy.$modal.confirm(`确认修改?`).then(function () {
      const data = {
        parentId: checkedKey.value.parentId,
        parentName: checkedKey.value.parentName,
        name: changeName.value,
        id: checkedKeyId.value,
      };
      roleCreate(data).then((res) => {
        if (res.code == 20000) {
          rolesList();
          ElMessage.success('修改成功！');
        }
      });
      dialogVisible2.value = false;
    });
  }
};

// 右边多选框
// 权限列表

// 点击所有权限
const handleCheckAllChange = (val) => {
  // 每次他的值会变成1，不知道为什么，先把他赋值为空
  checkedFirst.value =
    checkedFirst.value == 1 ? (checkedFirst.value = []) : checkedFirst.value;
  if (val) {
    checkedFirst.value = rules.value.map((item) => (val ? item.name : ''));
    for (const v of checkedFirst.value) {
      checkName.value = v;
      handleSecondChange(true, { target: { _value: v } });
    }
  } else {
    checkedFirst.value = [];
    checkedSecond.value = [];
  }
  // 点击所有，选中所有的id，保存的时候需要
  for (const v of rules.value) {
    if (val) {
      checkIds.value.push(v.id);
      for (const vv of v.children[1]) {
        checkIds.value.push(vv.id);
      }
      for (const vv of v.children[2]) {
        checkIds.value.push(vv.id);
      }
    } else {
      checkIds.value = checkIds.value.filter((i) => i != v.id);
      for (const vv of v.children[1]) {
        checkIds.value = checkIds.value.filter((i) => i != vv.id);
      }
      for (const vv of v.children[2]) {
        checkIds.value = checkIds.value.filter((i) => i != vv.id);
      }
    }
  }
  checkIds.value = [...new Set(checkIds.value)];
};
// 选择所有，让所有权限按钮选中
const handleCheckedFirstChange = (value) => {
  const checkedCount = value.length;
  checkAll.value = checkedCount === rules.value.length;
};

// 第二级
// 选中后的列表
const checkedSecond = ref([]);
const checkName = ref('');
const currentFirst = ref('');
// 二级
const handleSecondChange = (value, item, isHuiXian) => {
  currentFirst.value = item.target.value;
  // item.target._value  被选中的一级分类名称
  checkName.value = item.target._value ? item.target._value : checkName.value;
  for (const v of rules.value) {
    if (v.name == checkName.value) {
      v.roleIsHavePermission = value ? 1 : 0;
      if (v.children[1].length > 0) {
        for (const i of v.children[1]) {
          if (isHuiXian) {
            if (i.roleIsHavePermission == 1) {
              checkedSecond.value.push(i.name);
            }
          } else if (value) {
            checkedSecond.value.push(i.name);
          } else {
            checkedSecond.value = checkedSecond.value.filter(
              (item) => item != i.name
            );
            i.roleIsHavePermission = 0;
          }
        }
      }
      if (v.children[2].length > 0) {
        for (const i of v.children[2]) {
          if (isHuiXian) {
            if (i.roleIsHavePermission == 1) {
              checkedSecond.value.push(i.name);
            }
          } else if (value) {
            checkedSecond.value.push(i.name);
          } else {
            checkedSecond.value = checkedSecond.value.filter(
              (item) => item != i.name
            );
            i.roleIsHavePermission = 0;
          }
        }
      }
      // 存，删选择的权限id，保存的时候用
      if (v.roleIsHavePermission == 1) {
        checkIds.value.push(v.id);
        for (const vv of v.children[1]) {
          checkIds.value.push(vv.id);
        }
        for (const vv of v.children[2]) {
          checkIds.value.push(vv.id);
        }
      } else {
        checkIds.value = checkIds.value.filter((i) => i != v.id);
        for (const vv of v.children[1]) {
          checkIds.value = checkIds.value.filter((i) => i != vv.id);
        }
        for (const vv of v.children[2]) {
          checkIds.value = checkIds.value.filter((i) => i != vv.id);
        }
      }
    }
  }
  // 因为循环了很多次，选中的数据会存在很多重复数据，导致点击二级子集菜单的时候需要很多次才能取消选中，所以需要去重
  checkIds.value = [...new Set(checkIds.value)];
  checkedSecond.value = [...new Set(checkedSecond.value)];
};

// 二级子集
const handleCheckedSecondChange = (val) => {
  currentFirst.value = val.name;
  //当当前的二级菜单全选和反选的时候对应的全选按钮也选中和反选
  // 处理当前选中的二级菜单的变化
  const currentFirstIndex = rules.value.findIndex(
    (item) => item.name === currentFirst.value
  );
  if (currentFirstIndex !== -1) {
    const currentSecond = [
      ...rules.value[currentFirstIndex].children[1],
      ...rules.value[currentFirstIndex].children[2],
    ];
    const allChecked = currentSecond.every((subItem) =>
      checkedSecond.value.includes(subItem.name)
    );
    if (allChecked) {
      // 如果所有二级菜单都选中，则更新对应的一级菜单状态
      checkedFirst.value.push(currentFirst.value);
    } else {
      // 如果有二级菜单未选中，则将对应的一级菜单状态移除
      const index = checkedFirst.value.findIndex(
        (item) => item === currentFirst.value
      );
      if (index !== -1) {
        checkedFirst.value.splice(index, 1);
      }
    }
  }
  // 去重
  checkedFirst.value = [...new Set(checkedFirst.value)];
  checkAll.value = checkedFirst.value.length === rules.value.length;
};

// 点击二级菜单的子集
const secondChildrenChange = (val) => {
  // 只要点击了二级子集，就选中一级目录
  checkedFirst.value.push(
    rules.value.filter((i) => i.id == val.parentId)[0].name
  );
  checkIds.value.push(val.parentId);
  if (checkIds.value.includes(val.id)) {
    checkIds.value = checkIds.value.filter((i) => i != val.id);
  } else {
    checkIds.value.push(val.id);
  }
};

// 保存
function saveData() {
  var a = [];
  for (const v of rules.value) {
    for (const vv of v.children[1]) {
      if (vv.roleIsHavePermission == 1) {
        checkIds.value.push(v.id);
      }
    }
    for (const vv of v.children[2]) {
      if (vv.roleIsHavePermission == 1) {
        checkIds.value.push(v.id);
      }
    }
  }
  a = Array.from(new Set(checkIds.value))
    .slice()
    .sort((a, b) => a - b)
    .join(',');
  const data = {
    roleId: checkedKeyId.value,
    ruleId: a,
  };
  if (checkedKeyId.value) {
    appRuleUpdate(data).then((res) => {
      if (res.code == 20000) {
        ElMessage.success('保存成功！');
        permissionList();
      }
    });
  } else {
    ElMessage.warning('请选择二级分类');
  }
}
</script>

<style lang="scss" scoped>
:deep(.el-tooltip__trigger:focus-visible) {
  outline: unset;
}
.permisstion {
  display: flex;
  .plathName {
    color: red;
    font-size: 10px;
    margin-top: 3px;
  }
}
.box-card {
  margin: 20px;

  .card-header {
    font-size: 20px;
    font-weight: 600;
    color: #1d2129;
    padding: 10px;
    display: flex;
    flex-direction: row;
    align-items: center;
  }

  .countent {
    display: flex;
    flex-direction: row;

    .leftBox {
      width: 25%;

      .leftBox-header {
        padding: 10px 30px 20px 0;
        display: flex;
        justify-content: space-between;

        .action-icon-all {
          width: 100px;
          border-radius: 10px;
          box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
          border: 1px solid #e5e6eb;
          position: absolute;
          z-index: 1;
          top: 140px;
          left: 180px;
          background-color: white;

          .action-icon {
            width: 60px;
            height: 20px;
            font-size: 14px;
            margin: 10px 0 10px 10px;
            display: inline-block;
          }
        }
      }
    }

    .rightBox {
      width: 85%;
      padding-left: 30px;
      border-left: 1px solid rgb(235, 237, 240);

      .breadcrumb {
        .breadcrumb-dome {
          height: 40px;
          line-height: 40px;
          font-size: 20px;
        }
      }

      .checkList {
        .checkList-item {
          margin-bottom: 30px;
          display: flex;
          flex-direction: column;

          .checkList-item-children {
            display: flex;
            flex-direction: column;

            .checkList-item-children-span {
              font-size: 14px;
              color: #86909c;
              padding-right: 35px;
            }
          }
        }
      }
    }
  }

  .dialog {
    .dialog-countent {
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      .order {
        width: 4000px;
        height: 40px;
        display: flex;
        flex-direction: row;
        align-items: center;

        span {
          margin-right: 20px;
        }
      }

      .first-order {
        margin: 10px 0 40px 30px;

        .first-order-select {
          height: 40px;
        }
      }

      .Second-order {
        margin: 10px 0 80px 30px;

        .Second-order-input {
          height: 40px;
        }
      }
    }
  }
}
</style>
